"""
异常处理和速率限制示例
演示如何使用异常处理框架和速率限制机制
"""
import time
import logging
import sys
from typing import List, Dict

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)]
)

# 导入LLM适配层
from lib.llm import (
    complete, create_provider, rate_limit, provider_rate_limit,
    LLMException, AuthenticationError, RateLimitError, ServerError
)


def example_error_handling():
    """演示异常处理"""
    print("\n=== 异常处理示例 ===")
    
    # 尝试使用无效的API密钥
    try:
        provider = create_provider(overrides={
            "provider": "anthropic",
            "model": "claude-3-5-sonnet",
            "api_key": "invalid-api-key"
        })
        
        response = provider.complete([{"role": "user", "content": "你好"}])
        print(f"响应: {response}")
    except AuthenticationError as e:
        print(f"认证错误: {e}")
        print(f"提供商: {e.provider}, 模型: {e.model}")
        print(f"详情: {e.details}")
    except RateLimitError as e:
        print(f"速率限制错误: {e}")
        print(f"重试建议时间: {e.retry_after}秒")
    except ServerError as e:
        print(f"服务器错误: {e}")
    except LLMException as e:
        print(f"LLM错误: {e}")
    

# 普通速率限制装饰器示例
@rate_limit(max_calls=3, period=10.0, wait=False)
def limited_function(name: str) -> str:
    """使用速率限制装饰器的函数"""
    return f"你好, {name}!"


# 带等待的速率限制装饰器示例
@rate_limit(max_calls=2, period=5.0, wait=True)
def limited_function_with_wait(name: str) -> str:
    """使用带等待的速率限制装饰器的函数"""
    return f"你好, {name}!"


# 提供商特定的速率限制装饰器示例
@provider_rate_limit(provider="anthropic", model="claude-3-5-sonnet")
def call_anthropic_api(messages: List[Dict[str, str]]) -> str:
    """调用Anthropic API并使用自动速率限制"""
    # 这里通常会调用actual_anthropic_api
    # 但为了示例，我们只是返回一个模拟响应
    return "这是来自Anthropic API的模拟响应"


def example_rate_limit():
    """演示速率限制"""
    print("\n=== 速率限制示例 ===")
    
    print("\n1. 基本速率限制 (不等待，抛出异常)")
    try:
        for i in range(5):
            result = limited_function(f"用户{i}")
            print(f"调用 {i+1}: {result}")
    except RateLimitError as e:
        print(f"到达速率限制: {e}")
    
    print("\n2. 带等待的速率限制")
    for i in range(5):
        start_time = time.time()
        result = limited_function_with_wait(f"用户{i}")
        elapsed = time.time() - start_time
        print(f"调用 {i+1}: {result} (用时: {elapsed:.2f}秒)")
    
    print("\n3. 提供商特定的速率限制")
    for i in range(3):
        messages = [{"role": "user", "content": f"这是消息 {i+1}"}]
        result = call_anthropic_api(messages)
        print(f"API调用 {i+1}: {result}")


if __name__ == "__main__":
    # 演示异常处理
    example_error_handling()
    
    # 演示速率限制
    example_rate_limit()
